package thinkinginspring.spring.bean.definition;

import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import thinking.in.spring.ioc.container.overview.domain.User;
import thinking.in.spring.ioc.container.overview.factory.UserFactory;
import thinking.in.spring.ioc.container.overview.factory.impl.DefaultUserFactory;
import java.util.Iterator;
import java.util.ServiceLoader;
import static java.util.ServiceLoader.load;

/**
 * Bean 实例化的特性方式
 * - 通过ServiceLoader实现
 * - 通过AutoWireCapableFactoryBean#creaBean(java.lang.String,int,boolean)
 */
public class SpecialBeanInstanceDemo
{
    public static void main(String[] args)
    {
        String location = "classpath:META-INF/special-bean-creation-context.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(location);

        AutowireCapableBeanFactory beanFactory = applicationContext.getAutowireCapableBeanFactory();
        //直接通过Java api创建
        System.out.println("直接通过Java api创建==================");
        demoServiceLoader();
        //通过ServiceLoaderFactoryBean来创建
//        System.out.println("通过ServiceLoaderFactoryBean来创建==================");
//        ServiceLoader<UserFactory> loader =
//                beanFactory.getBean("serviceLoaderUserFactoryBean", ServiceLoader.class);
//        disServiceLoader(loader);
//        System.out.println(beanFactory.getBean(UserFactory.class).getClass());

        //通过serviceFactoryBean来创建
        System.out.println("通过serviceFactoryBean来创建==================");
        System.out.println(beanFactory.getBean(UserFactory.class).createUser());

        System.out.println("通过AutowireCapableBeanFactory 实例化UserFactory==================");
        //AutowireCapableBeanFactory 实例化UserFactory
        System.out.println(beanFactory.createBean(DefaultUserFactory.class).createUser());
        System.out.println(beanFactory.getBean(UserFactory.class).createUser());

        System.out.println("通过AutowireCapableBeanFactory 实例化user==================");
        //AutowireCapableBeanFactory 实例化user
        User user = beanFactory.createBean(User.class);
        System.out.println(user);
    }

    private static void demoServiceLoader()
    {
        ServiceLoader<UserFactory> loader = load(UserFactory.class, Thread.currentThread().getContextClassLoader());
        disServiceLoader(loader);
    }

    private static void disServiceLoader(ServiceLoader<UserFactory> loader)
    {

        Iterator<UserFactory> iterator = loader.iterator();
        while (iterator.hasNext())
        {
            UserFactory userFactory = iterator.next();
            System.out.println(userFactory.createUser());
        }
    }
}



